<template>
    <div class="index app-wrapper">
        <div class="tab-header"
            v-if="isFixedTabheader"
            :class="{'fixed': isFixedTabheader}"
        >
            <ul class="tab-header-list">
                <li class="tab-header-item" 
                    :class="{'active': activeTab === 'lives'}"
                    @click="switchChannel('lives')"
                ><span>话题</span></li>
                <li class="tab-header-item"
                    :class="{'active': activeTab === 'channels'}"
                    @click="switchChannel('channels')"
                ><span>频道</span></li>
                <li class="tab-header-item"
                    :class="{'active': activeTab === 'videos'}"
                    @click="switchChannel('videos')"
                ><span>小视频</span></li>
            </ul>
        </div>
        <mescroll-vue 
            ref="mescroll" 
            :up="mescrollUp" 
            :down="mescrollDown"
            @init="mescrollInit"
            class="content-slide"
        >
            <div class="content-slide-scroller" ref="contentScroller">
                <div class="head-panel" ref="headPanel">
                    <SwiperBanner :bannerList="banners"></SwiperBanner>
                    <div class="header-bar">
                        <div class="research"><router-link to="/research" class="phoney-input"><i class="van-icon van-icon-search"></i>搜索话题/频道/小视频</router-link></div>    
                        <span class="public-number">
                            <i></i><p>公众号</p>
                        </span>
                    </div>
                    <div class="owner-wrapper">
                        <OwnerMedia 
                            :ownerInfo="owner"
                            @show-follow-panel="showCodeDialog = true"
                        ></OwnerMedia>
                    </div>
                </div>
                <!-- /head-panel -->

                <div class="tab" ref="tab">
                    <div class="tab-header" ref="tabHeader" 
                        v-if="!isFixedTabheader"
                        :class="{'fixed': isFixedTabheader}"
                        :style="{'top': tabHeaderTop + 'px'}"
                    >
                        <ul class="tab-header-list">
                            <li class="tab-header-item" 
                                :class="{'active': activeTab === 'lives'}"
                                @click="switchChannel('lives')"
                            ><span>话题</span></li>
                            <li class="tab-header-item"
                                :class="{'active': activeTab === 'channels'}"
                                @click="switchChannel('channels')"
                            ><span>频道</span></li>
                            <li class="tab-header-item"
                                :class="{'active': activeTab === 'videos'}"
                                @click="switchChannel('videos')"
                            ><span>小视频</span></li>
                        </ul>
                    </div>
                    <div class="tab-body" ref="tabBody" :class="{'fixed': isFixedTabheader}">
                        <div class="tab-body-item" v-show="activeTab === 'lives'">
                            <div class="topic-types-wrapper" ref="categoryWrapper">
                                <div class="topic-types-list" ref="categorScroller">
                                    <a href="#" class="topic-types-item" 
                                        :class="{'active': selectedCategory === 0}"
                                        @click="loadLivesByCategory(0)"
                                    >全部</a>
                                    <a href="#" class="topic-types-item"
                                        v-for="item in category"
                                        :key="item.id"
                                        :class="{'active': selectedCategory === item.id}"
                                        @click="loadLivesByCategory(item.id)"
                                    >{{item.name}}</a>
                                </div>
                            </div>
                            <ul class="topic-list">
                                <TopicItem
                                    v-for="item in filteredLives"  
                                    :topic="item" 
                                    :key="item.id"
                                    href="/channel"
                                ></TopicItem>
                            </ul>
                            <div class="all-loaded text-center" v-if="livesNone">已加载全部</div>
                        </div>
                        <!-- /话题 -->
                        <div class="tab-body-item" v-show="activeTab === 'channels'">
                            <ul class="channel-list">
                                <ChannelItem 
                                    v-for="item in channels"
                                    :key="item.id"
                                    :channel="item"
                                    href="/channel"
                                ></ChannelItem>
                            </ul>
                            <div class="all-loaded text-center" v-if="channelsNone">已加载全部</div>
                        </div>
                        <!-- /频道 -->
                        <div class="tab-body-item" v-show="activeTab === 'videos'">
                            <ul class="video-list">
                                <SmallVideo
                                    v-for="item in videos"
                                    :video="item"
                                    :key="item.id"
                                    isCtrl="false"
                                ></SmallVideo>
                            </ul>
                            <div class="all-loaded text-center" v-if="videosNone">已加载全部</div>
                        </div>
                        <!-- /小视频 -->
                    </div>
                </div>
                <div class="text-center no-more" v-if="modalNums == 5"> 没有更多了...</div>
            </div>
        </mescroll-vue>
        <!-- /content-slide -->
        <div class="fixed-bottom-nav" ref="bottomNav">
            <ul class="nav-list">
                <li>
                    <router-link to="/index" class="nav-item">
                        <span><i class="icon img-icon-home"></i><p>首页</p></span>
                    </router-link>
                </li>
                <li>
                    <router-link to="/mine" class="nav-item">
                        <span><i class="icon img-icon-user"></i><p>我的</p></span>
                    </router-link>
                </li>
            </ul>
        </div>
        <!-- /fixed-bottom-nav -->

        <van-popup v-model="showCodeDialog" class="code-dialog">
        <CodeDialog
            @close-2vcode-dialog="showCodeDialog = false"
        ></CodeDialog>
        </van-popup>
    </div>
</template>

<script>
import CodeDialog from '@/components/CodeDialog';
import BScroll from '@better-scroll/core';
import SwiperBanner from '@/components/SwiperBanner';
import OwnerMedia from '@/components/OwnerMedia';
import TopicItem from '@/components/TopicItem';
import ChannelItem from '@/components/ChannelItem';
import SmallVideo from '@/components/SmallVideo';
import {getIndexInfomation, getCateLives, getCateChannels, getCateVideos} from '@/api';
import MescrollVue from 'mescroll.js/mescroll.vue'
import { setTimeout } from 'timers';

export default {
    components: {
        SwiperBanner,
        OwnerMedia,
        TopicItem,
        ChannelItem,
        SmallVideo,
        MescrollVue,
        CodeDialog 
    },
    props: {},
    data() {
        return {
            showCodeDialog: false,
            activeTab: 'lives',  // 当前高亮栏目
            banners: [],
            category: [],
            selectedCategory: 0,
            lives:[],
            channels: [],
            videos: [],
            liveMaps: {},
            channelMaps: {},
            videoMaps: {},
            livesNone: false,       // 话题是否没有更多
            channelsNone: false,    // 频道是否没有更多
            videosNone: false,      // 小视频是否没有更多
            owner: {
                name: '名人字画私人订制',
                imgSrc: require('@/assets/img/avatar.jpg'),
                visits: 25000,
                id: 1
            },
            categoryScroll: null,
            isFixedTabheader: false,
            tabHeaderTop: 0,
            isLoadingMore: false,
            isLastPage: false,
            modalNums: 0,
            modalLives: [], // 用于模拟加载的数据

            // 滚动条
            mescroll: null,
            mescrollDown: {
                isLock: true
            },
            mescrollUp:{
                auto: false,
                callback: this.upCallback,
                noMoreSize: 3,
                onScroll: this.onContentSlideScroll
            }
        };
    },
    computed: {
        filteredLives(){
            if(this.selectedCategory === 0) return this.lives;
            return this.lives.filter((item)=>{
                return item.id;
            });
        }
    },
    created() {
        getIndexInfomation().then((response)=>{
            console.log(response)
            if(response.code === 0){
                let results = response.data;
                this.liveMaps = results.lives
                this.lives = results.lives.data;
                this.banners = results.banners;
                this.category = results.category;
                this.channels = results.channels.data;
                this.videos = results.videos.data;
                this.channelMaps = results.channels;
                this.videoMaps = results.videos;

                this.livesNone = (this.liveMaps['current_page'] === this.liveMaps['last_page']);
                this.channelsNone = (this.channelMaps['current_page'] === this.channelMaps['last_page']);
                this.videosNone = (this.videoMaps['current_page'] === this.videoMaps['last_page']);

                this.createCategoryScroll();
            }
        });
    },
    methods: {
        // mescroll组件初始化的回调,可获取到mescroll对象
        mescrollInit (mescroll) {
            this.mescroll = mescroll;  // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
        },
        upCallback(){
            if(this.activeTab === 'lives'){
                console.log('here')
                if(this.livesNone) return;
                getCateLives({page: this.liveMaps.current_page + 1, cateId: this.selectedCategory}).then((response)=>{
                    let responseData = response.data
                    this.lives = [...this.lives, ...responseData.data];
                    //this.liveMaps = {...this.liveMaps, ...responseData};
                    this.liveMaps = responseData;
                    this.upSuccessCallback(this.activeTab);
                });
            }else if(this.activeTab === 'channels'){
                if(this.channelsNone) return;
                getCateChannels(this.channelMaps.current_page + 1).then((response)=>{
                    let responseData = response.data
                    this.channels = [...this.channels, ...responseData.data];
                    this.channelMaps = {...this.channelMaps, ...responseData};
                    this.upSuccessCallback(this.activeTab);
                })

            }else if(this.activeTab === 'videos'){
                if(this.videosNone) return;
                getCateVideos(this.videoMaps.current_page + 1).then((response)=>{
                    let responseData = response.data
                    this.videos = [...this.videos, ...responseData.data];
                    this.videoMaps = {...this.videoMaps, ...responseData};
                    this.upSuccessCallback(this.activeTab);
                })
            }
            
        },
        upSuccessCallback(type){
            let maps = {
                'lives': 'livesNone',
                'channels': 'channelsNone',
                'videos': 'videosNone'
            };

            let judgeData;
            let mescrollStatus = false;
            if(this.activeTab == 'lives'){
                judgeData = this.liveMaps;
            }else if(this.activeTab == 'channels'){
                judgeData = this.channelMaps;
            }else {
                judgeData = this.videoMaps;
            }

            this[maps[type]] = (judgeData.current_page === judgeData.last_page);
            //this.mescroll.endSuccess(judgeData.current_page === judgeData.last_page);

            this.$nextTick(()=>{
                console.log(this[type].length, judgeData.last_page > judgeData.current_page)
                this.mescroll.endSuccess(this[type].length, false);
            });
            
        },
        onContentSlideScroll(scroll, offsetY){
            let headPanelHeight = this.$refs.headPanel.offsetHeight;

            setTimeout(()=>{
                this.isFixedTabheader = Math.abs(offsetY) >= headPanelHeight;
                this.tabHeaderTop = offsetY > 0 ? 0 : Math.abs(offsetY);
            }, 30)
            
        },
        contentSlideCallback(){
            let contentSlide = this.$refs.contentSlide;
            let contentSlideHeight = this.$refs.contentSlide.offsetHeight;
            let contentScrollerHeight = this.$refs.contentScroller.offsetHeight;
            let headPanelHeight = this.$refs.headPanel.offsetHeight;
            let scrollTop = contentSlide.scrollTop;

            // 设置tab-header固定
            this.isFixedTabheader = scrollTop >= headPanelHeight;
            // 判断滚动到什么位置的时候加载更多数据

            if(scrollTop >= contentScrollerHeight - contentSlideHeight - 30){
                if(this.isLoadingMore) return;
                //if(!this.isLastPage) this.loadMore();
            }
        },
        switchChannel(channel){
            if(this.activeTab === channel) return;
            this.activeTab = channel;
            this.mescroll.scrollTo(0, 0) // 刷新列表数据
        },
        loadLivesByCategory(categoryId){
            this.selectedCategory = categoryId;
            
            getCateLives({page: 1, cateId: this.selectedCategory}).then((response)=>{
                let responseData = response.data
                this.lives = responseData.data;
                this.liveMaps = {...this.liveMaps, ...responseData};
                //this.liveMaps = responseData;
                this.upSuccessCallback(this.activeTab);
            });
        },
        createCategoryScroll(){
            this.$nextTick(()=>{
                this.$refs.categorScroller.style.width = this.getCategorScrollerWidth() + 'px';

                if(this.$refs.categorScroller.querySelectorAll('.topic-types-item').length < 2) return;
                if(!this.categoryScroll){
                    this.categoryScroll = new BScroll(this.$refs.categoryWrapper, {
                        startX: 0,
                        click: true,
                        scrollX: true,
                        // 忽略竖直方向的滚动
                        scrollY: false,
                        eventPassthrough: "vertical"
                    });
                }else{
                    this.categoryScroll.refresh();
                }
            });

        },
        getCategorScrollerWidth(){
            let width = 0;
            let categoryItems = this.$refs.categorScroller.querySelectorAll('.topic-types-item');
            let marginRight = categoryItems[1].offsetLeft - categoryItems[0].offsetLeft - categoryItems[0].offsetWidth;

            return [...categoryItems].reduce((width, item)=>{
                let itemWidth = item.offsetWidth + marginRight;
                return width + itemWidth;
            }, 0);
        }
    },
};
</script>
<style lang="scss" scoped>
    $nav-height: 100px;
.index {
    padding-bottom: $nav-height;

    .content-slide {
        height: 100%;
        position: relative;
    }
    .header-bar {
        display: flex;
        position: absolute;
        top: 24px;
        left: 36px;
        right: 36px;
        z-index: 10;
        font-size: 24px;
        color: #fff;
    }

    .research {
        flex: 1;
        margin-right: 30px;
    }

    .phoney-input {
        display: flex;
        height: 70px;
        padding: 15px 24px;
        align-items: center;
        color: #fff;
        background-color: rgba(255,255,255,0.25);
        border-radius: 35px;

        .van-icon {
            display: inline-block;
            margin-right: 10px;
            font-size: 32px;
        }
    }


    .public-number {
        font-size: 24px;
        text-align: center;
        i {
            display: inline-block;
            width: 42px;
            height: 42px;
            vertical-align: middle;
            background: url() no-repeat;
            background-size: contain;
        }
    }

    .owner-wrapper {
        padding: 0 36px;
        background-color: #fff;
    }
}

.tab { margin-top: 24px; }


.tab-header {
    height: $nav-height;
    border-bottom: 1px solid #f0f0f0;
    font-size: 28px;
    background-color: #fff;
    &.fixed{
        position: fixed;
        width: 100%;
        top: 0;
        z-index: 20;
    }
    .tab-header-list {
        display: flex;
    }

        

    .tab-header-item {
        color: #2a2a2a;
        position: relative;
        text-align: center;
        flex: 1;
        span {
            display: inline-block;
            line-height: 100px;
            position: relative;
        }
        &.active{ 
            color: #0084ff; 
            span:after {
                content: '';
                width: 100%;
                height: 4px;
                position: absolute;
                left: 0;
                bottom: 0;
                background-color: #0084ff; 
            }  
        }

    }
}

.tab-body {
    &.fixed {
        margin-top: 124px;
    }
}
.tab-body-item {
    background-color: #fff;
}

.topic-types-wrapper {
    height: 84px;
    margin: 0 35px;
    font-size: 0;
    overflow: hidden;

    > .topic-types-list {
        box-sizing: content-box;
        height: 48px; 
        padding: 18px 0; 
        white-space: nowrap;
    }
}
.topic-types-item {
    display: inline-block;
    height: 48px;
    padding: 0 20px;
    border: 1px solid #747474;
    margin-right: 24px;
    font-size: 24px;
    color: #747474;
    line-height: 48px;
    border-radius: 24px;
    &.active {
        border-color: #0084ff;
        color: #fff;
        background-color: #0084ff;
    }
}

.fixed-bottom-nav {
    position: fixed;
    width: 100%;
    bottom: 0;
    background-color: #fff;
    box-shadow: 0px 3px 9px rgba(0,0,0,0.15);
    text-align: center;
    
    .nav-list {
        display: flex;
        > li {
            flex: 1;
        }
    }

    .nav-item {
        height: 100px;
        line-height: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        color: #747474;
        &.active { color: #0084ff; }

        span {
            display: inline-block;
            padding-top: 4px;
        }

        i {
            display: inline-block;
            width: 40px;
            height: 48px;
            margin-bottom: 8px;
            background-size: contain;
        }
    }
}



</style>